package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supervisor.SupervisorProjectMilepost;
import com.qili.entity.supervisor.SupervisorProjectStage;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectStageDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.*;
import com.qili.service.supervisor.*;
import com.qili.service.sys.SysRegionService;
import com.qili.util.StringUtil;
import com.qili.util.UploadUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/2/25
 * @description 里程碑延期job
 */
@Log
public class LcYqJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupervisorProjectService supervisorProjectService;
    @Autowired
    private DataSourceTransactionManager manager;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SysRegionService sysRegionService;

    @Autowired
    SupervisorFileService supervisorFileService;

    @Autowired
    SupervisorProjectStageService supervisorProjectStageService;
    @Autowired
    SupervisorProjectMilepostService supervisorProjectMilepostService;

    @Autowired
    UploadUtil uploadUtil;

    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectLeaderService projectLeaderService;
    @Autowired
    ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    ProjectTypeService projectTypeService;
    @Autowired
    BaseStageService baseStageService;
    @Autowired
    BaseMilepostService baseMilepostService;
    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    SupervisorProjectPayService supervisorProjectPayService;
    @Autowired
    SupervisorProjectFormsDataService supervisorProjectFormsDataService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    ProjectAdminService projectAdminService;
    @Autowired
    SupervisorPayRecordService supervisorPayRecordService;
    @Autowired
    ProjectBigEventService projectBigEventService;
    @Autowired
    ProjectSealRecordService projectSealRecordService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("LcYqJob：启动任务=======================");

        log.info("LcYqJob=======开始==================================");
        String lockkey = "LcYqJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            run();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            unlock(lockkey, uuId);
        }
        System.out.println("LcYqJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {
        //001 未提交
        //002 未启动
        //003 已完成
        //004 进行中
        //005 已延期
        // 002 004 005  提交没有完成的项目 里程延期自动计算
        // 查询项目
        String[] stus = new String[3];
        stus[0] = "002";
        stus[1] = "004";
        stus[2] = "005";
        //遍历项目
        try {
            List<SupervisorProjectDTO> listpro = supervisorProjectService.selectProList(stus);
            for (int b = 0; b < listpro.size(); b++) {

                /*项目Id*/
                String proId = listpro.get(b).getId();
                SupervisorProjectStageDTO dto = new SupervisorProjectStageDTO();
                dto.setProjectId(proId);
                List<SupervisorProjectStageDTO> listStage = supervisorProjectStageService.selectProjectStage(dto);
                Boolean isProjectYc = false;
                /*判断项目阶段和里程 是否延期*/
                for (int i = 0; i < listStage.size(); i++) {
                    SupervisorProjectStageDTO stageDTO = listStage.get(i);
                    String stageId = stageDTO.getId();
                    String stageNo = stageDTO.getStageNo();
                    if (!"005".equals(stageNo)) {
                        SupervisorProjectStage stage = supervisorProjectStageService.selectByPrimaryKey(stageId);
                        /*获取里程*/
                        SupervisorProjectMilepost milepost = new SupervisorProjectMilepost();
                        milepost.setSupervisorProjectStageId(stageId);
                        List<SupervisorProjectMilepost> listMilepost = supervisorProjectMilepostService.select(milepost);
                        Boolean isyc = false;
                        Boolean jdstatus = false;
                        /*处理里程延迟状态*/
                        HashMap<String, Boolean> map = updateLcStatus(listMilepost, stage, jdstatus, isyc, isProjectYc);
                        isyc = map.get("isyc");
                        jdstatus = map.get("jdstatus");
                        isProjectYc = map.get("isProjectYc");
                        // 遍历项目里程结束
                        if (isyc) {
                            /*里程延迟  阶段就延期  该项目就延期*/
                            if (!"3".equals(stage.getFinishStatus())) {
                                stage.setFinishStatus("3");
                                supervisorProjectStageService.updateByPrimaryKey(stage);
                            }
                        } else {
                            // 没有存在延期的里程，还原阶段状态
                            if ("3".equals(stage.getFinishStatus()) && stage.getFinishDate() == null) {
                                if (jdstatus) {
                                    stage.setFinishStatus("1");
                                    supervisorProjectStageService.updateByPrimaryKey(stage);
                                } else {
                                    stage.setFinishStatus("0");
                                    supervisorProjectStageService.updateByPrimaryKey(stage);
                                }
                            }
                        }

                    }
                }
                SupervisorProject project = listpro.get(b);
                System.out.println(project.toString() + "jjjj");
                if (isProjectYc) {
                    project.setStatus("005");
                    supervisorProjectService.updateByPrimaryKey(project);
                } else {
                    // 没有延期的里程
                    if ("005".equals(project.getStatus())) {
                        //001 未提交
                        //002 未启动
                        //003 已完成
                        //004 进行中
                        //005 已延期
                        if (StringUtil.isNotBlank(project.getFinishDate())) {
                            //003 已完成
                            project.setStatus("003");
                            String content = "延期定时任务，" + project.toString();
                            supervisorProjectService.insertFileLog(content, "延期定时任务", project.getId());
                        } else if (StringUtil.isNotBlank(project.getStartTime())) {
                            //004 进行中
                            project.setStatus("004");
                        } else if (StringUtil.isNotBlank(project.getCommitDate())) {
                            //002 未启动
                            project.setStatus("002");
                        } else {
                            //001 未提交
                            project.setStatus("001");
                        }
                        supervisorProjectService.updateByPrimaryKey(project);
                    }
                }

            }
            System.out.println("JobDemo1：执行完毕=======================");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @param listMilepost
     * @param stage
     * @param jdstatus
     * @param isyc
     * @param isProjectYc
     * @Author:zhaoyongke
     * @Description:
     * @Date:19:03 2021/3/5
     */
    public HashMap<String, Boolean> updateLcStatus(List<SupervisorProjectMilepost> listMilepost, SupervisorProjectStage stage, Boolean jdstatus, Boolean isyc, Boolean isProjectYc) throws Exception {
        HashMap<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("jdstatus", jdstatus);
        map.put("isyc", isyc);
        map.put("isProjectYc", isProjectYc);
        for (int j = 0; j < listMilepost.size(); j++) {
            SupervisorProjectMilepost milepostl = listMilepost.get(j);
            String finishDate = milepostl.getFinishDate();
            if (StringUtil.isBlank(finishDate)) {
                /*002代表查看项目时候自动计算   001 点击完成按钮时候计算 状态*/
                String lcstatus = supervisorProjectService.updategetLcStatus(stage, milepostl, "002");
                if (StringUtil.isNotBlank(lcstatus)) {
                    // 还原里程状态为 未延期
                    Boolean isjx = false;
                    String step_num = milepostl.getStepNum();
                    String[] ayStatus = step_num.split(",");
                    for (int y = 0; y < ayStatus.length; y++) {// 判断是否都完成以2结尾的数量统计
                        if (ayStatus[y].trim().substring(1, 2).equals("1") || ayStatus[y].trim().substring(1, 2).equals("2")) {
                            isjx = true;
                            jdstatus = true;
                            map.put("jdstatus", true);
                            break;
                        }
                    }
                    if ("3".equals(lcstatus)) {
                        /*延迟*/
                        milepostl.setFinishStatus("3");
                        supervisorProjectMilepostService.updateByPrimaryKey(milepostl);
                        /*里程延迟*/
                        isyc = true;
                        map.put("isyc", true);
                        /*项目延迟*/
                        isProjectYc = true;
                        map.put("isProjectYc", true);
                    } else {
                        //未延期
                        if ("3".equals(milepostl.getFinishStatus())) {
                            if (isjx) {
                                milepostl.setFinishStatus("1");
                                supervisorProjectMilepostService.updateByPrimaryKey(milepostl);
                            } else {
                                milepostl.setFinishStatus("0");
                                supervisorProjectMilepostService.updateByPrimaryKey(milepostl);
                            }
                        }
                    }
                }
            }
        }

        return map;
    }

    public void lock(String key, String uuId) {
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

}
